package com.ruoyi.common.utils;

import com.ruoyi.common.config.RuoYiConfig;
import org.apache.commons.io.FilenameUtils;
import org.apache.poi.hssf.usermodel.HSSFPrintSetup;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.RegionUtil;
import org.apache.poi.util.Units;
import org.apache.poi.xssf.usermodel.*;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.function.Consumer;

public class ExcelWriter {
    private XSSFWorkbook workbook;
    private XSSFSheet currentSheet;
    private Row currentRow;

    private int rowIndex = 0;
    private int cellIndex = 0;

    public ExcelWriter() {
        workbook = new XSSFWorkbook();
    }

    public ExcelWriter createSheet(String sheetName) {
        currentSheet = workbook.createSheet(sheetName);
        currentSheet.setDefaultColumnWidth(19);
        currentSheet.setDefaultRowHeight((short) 700);
        XSSFPrintSetup printSetup = currentSheet.getPrintSetup();
        printSetup.setPaperSize(HSSFPrintSetup.A4_PAPERSIZE);
        printSetup.setScale((short) 55);
        rowIndex = 0;
        return this;
    }

    public ExcelWriter createSheet(String sheetName, short scale) {
        currentSheet = workbook.createSheet(sheetName);
        currentSheet.setDefaultColumnWidth(19);
        currentSheet.setDefaultRowHeight((short) 700);
        XSSFPrintSetup printSetup = currentSheet.getPrintSetup();
        printSetup.setPaperSize(HSSFPrintSetup.A4_PAPERSIZE);
        printSetup.setScale(scale);
        rowIndex = 0;
        return this;
    }

    public ExcelWriter createSheet(String sheetName, Short columnWidth, Short rowHeight) {
        currentSheet = workbook.createSheet(sheetName);
        if (columnWidth != null)
            currentSheet.setDefaultColumnWidth(columnWidth);
        if (rowHeight != null)
            currentSheet.setDefaultRowHeight((short) (rowHeight * 256));
        rowIndex = 0;
        return this;
    }

    public static void main(String[] args) throws Exception {
        FileWriter writer = new FileWriter("d:aa.txt");
        writer.write("jkfsdjf");
        ExcelWriter excelWriter = new ExcelWriter();
//        excelWriter
    }

    public void write(OutputStream outputStream) throws Exception {
        try (OutputStream outputStream1 = outputStream) {
            workbook.write(outputStream1);
        }
    }

    public XSSFCellStyle defaultCellStyle() {
        XSSFCellStyle globalCellStyle = workbook.createCellStyle();
        //DataFormat format = workbook.createDataFormat();
        //globalCellStyle.setDataFormat(format.getFormat("yyyy-MM-dd"));
        globalCellStyle.setWrapText(true);
        globalCellStyle.setBorderBottom(BorderStyle.MEDIUM);
        globalCellStyle.setBorderLeft(BorderStyle.MEDIUM);
        globalCellStyle.setBorderRight(BorderStyle.MEDIUM);
        globalCellStyle.setBorderTop(BorderStyle.MEDIUM);
        globalCellStyle.setAlignment(HorizontalAlignment.CENTER);
        globalCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        globalCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        globalCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());

        XSSFFont font = workbook.createFont();
        font.setFontName("黑体");
        font.setFontHeightInPoints((short) 12);
        globalCellStyle.setFont(font);
        return globalCellStyle;
    }

    public void setFontSize(Cell cell, short fontSize) {
        XSSFCellStyle cellStyle = (XSSFCellStyle) cell.getCellStyle();
        XSSFFont font = cellStyle.getFont() == null ? workbook.createFont() : cellStyle.getFont();
        font.setFontHeightInPoints(fontSize);
        //cellStyle.setFont(font);
        //cell.setCellStyle(cellStyle);
    }

    public void setFontSize(Cell cell, short fontSize, boolean bold) {
        XSSFCellStyle cellStyle = (XSSFCellStyle) cell.getCellStyle();
        XSSFFont font = cellStyle.getFont() == null ? workbook.createFont() : cellStyle.getFont();
        font.setFontHeightInPoints(fontSize);
        font.setBold(bold);
        //cellStyle.setFont(font);
        //cell.setCellStyle(cellStyle);
    }

    public void setFontSize(Cell cell, boolean bold) {
        XSSFCellStyle cellStyle = (XSSFCellStyle) cell.getCellStyle();
        XSSFFont font = cellStyle.getFont() == null ? workbook.createFont() : cellStyle.getFont();
        font.setBold(bold);
        //cellStyle.setFont(font);
        //cell.setCellStyle(cellStyle);
    }

    public Row writeRow(Consumer<Row> consumer) {
        currentRow = currentSheet.createRow(rowIndex++);


        CellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        currentRow.setRowStyle(cellStyle);
        currentRow.getRowStyle().setFillPattern(FillPatternType.SOLID_FOREGROUND);
        currentRow.getRowStyle().setFillForegroundColor(IndexedColors.WHITE.getIndex());
        currentRow.setHeight(currentSheet.getDefaultRowHeight());
        cellIndex = 0;
        if (consumer != null) {
            consumer.accept(currentRow);
        }
        return currentRow;
    }

    public Cell writeCell(Consumer<Cell> cellConsumer) {
        Cell cell = currentRow.createCell(cellIndex++);
        XSSFCellStyle cellStyle = defaultCellStyle();
        cell.setCellStyle(cellStyle);
        if (cellConsumer != null) {
            cellConsumer.accept(cell);
        }
        return cell;
    }

    public Cell writeCellImage(Consumer<Cell> cellConsumer, String path) {
        Cell cell = currentRow.createCell(cellIndex++);
        XSSFCellStyle cellStyle = defaultCellStyle();
        cell.setCellStyle(cellStyle);
        File photoFile = new File(path);
        if (photoFile.exists()) {
            BufferedImage bufferedImage = null;
            try {
                bufferedImage = ImageIO.read(photoFile);
                ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
                ImageIO.write(bufferedImage, "png", byteArrayOut);
                byte[] data = byteArrayOut.toByteArray();
                XSSFDrawing drawingPatriarch = currentSheet.createDrawingPatriarch();
                XSSFClientAnchor anchor = new XSSFClientAnchor(480, 30, 700, 250, cell.getColumnIndex(), currentRow.getRowNum(), cell.getColumnIndex() + 1, currentRow.getRowNum() + 1);
//                XSSFClientAnchor anchor = new XSSFClientAnchor(480, 30, 700, 250, (short)9, currentRow.getRowNum(), (short) 10, currentRow.getRowNum() + 1);
                drawingPatriarch.createPicture(anchor, workbook.addPicture(data, XSSFWorkbook.PICTURE_TYPE_JPEG));
                currentSheet.setColumnWidth((short) 500, (short) 500);
                currentRow.setHeight((short) 500);

            } catch (IOException e) {
                e.printStackTrace();
            }

        }


        if (cellConsumer != null) {
            cellConsumer.accept(cell);
        }
        return cell;
    }

    public void setColumnWidth(Cell cell, int width) {
        cell.getSheet().setColumnWidth(cell.getColumnIndex(), width);
    }

    public ExcelWriter emptyRowIndex() {
        rowIndex++;
        return this;
    }

    public ExcelWriter emptyColumnIndex() {
        cellIndex++;
        return this;

    }

    public Cell writeCell(int rowSpan, int columnSpan, Consumer<Cell> cellConsumer) {
        Cell cell = this.writeCell(cellConsumer);
        if (columnSpan > 0) {
            this.cellIndex = this.cellIndex + columnSpan;
        }
        CellRangeAddress addresses = new CellRangeAddress(currentRow.getRowNum(),
                currentRow.getRowNum() + rowSpan, cell.getColumnIndex(), cell.getColumnIndex() + columnSpan);
        if (rowSpan > 0 || columnSpan > 0) {
            currentRow.getSheet().addMergedRegion(addresses);
            RegionUtil.setBorderBottom(cell.getCellStyle().getBorderBottom(), addresses, currentSheet);
            RegionUtil.setBorderLeft(cell.getCellStyle().getBorderLeft(), addresses, currentSheet);
            RegionUtil.setBorderRight(cell.getCellStyle().getBorderRight(), addresses, currentSheet);
            RegionUtil.setBorderTop(cell.getCellStyle().getBorderTop(), addresses, currentSheet);
        }

        return cell;
    }

    public Cell writeCellImage(int rowSpan, int columnSpan, Consumer<Cell> cellConsumer, String imagePath) {
        Cell cell = this.writeCell(cellConsumer);
        if (columnSpan > 0) {
            this.cellIndex = this.cellIndex + columnSpan;
        }
        CellRangeAddress addresses = new CellRangeAddress(currentRow.getRowNum(),
                currentRow.getRowNum() + rowSpan, cell.getColumnIndex(), cell.getColumnIndex() + columnSpan);
        if (rowSpan > 0 || columnSpan > 0) {
            currentRow.getSheet().addMergedRegion(addresses);
            RegionUtil.setBorderBottom(cell.getCellStyle().getBorderBottom(), addresses, currentSheet);
            RegionUtil.setBorderLeft(cell.getCellStyle().getBorderLeft(), addresses, currentSheet);
            RegionUtil.setBorderRight(cell.getCellStyle().getBorderRight(), addresses, currentSheet);
            RegionUtil.setBorderTop(cell.getCellStyle().getBorderTop(), addresses, currentSheet);
        }

        String ext = FilenameUtils.getExtension(imagePath);
        if(StringUtils.isNotEmpty(imagePath)){
            imagePath=imagePath.replaceAll("/profile","");
        }
        imagePath.replaceAll("/profile","");
        File photoFile = null;
        if(StringUtils.isNotEmpty(RuoYiConfig.getProfile())){
            photoFile= new File(RuoYiConfig.getProfile()+imagePath);
        }
        if(!photoFile.exists()){
            if(StringUtils.isNotEmpty(RuoYiConfig.getProfile1())){
                photoFile= new File(RuoYiConfig.getProfile1()+imagePath);
            }
        }
        if(!photoFile.exists()){
            if(StringUtils.isNotEmpty(RuoYiConfig.getProfile2())){
                photoFile= new File(RuoYiConfig.getProfile2()+imagePath);
            }
        }
        if(!photoFile.exists()){
            if(StringUtils.isNotEmpty(RuoYiConfig.getProfile3())){
                photoFile= new File(RuoYiConfig.getProfile3()+imagePath);
            }
        }
        if (photoFile.exists()) {
            BufferedImage bufferedImage = null;
            try {
                bufferedImage = ImageIO.read(photoFile);
                int widthPx = bufferedImage.getWidth();
                int heightPx = bufferedImage.getHeight();

                ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
                ImageIO.write(bufferedImage, ext, byteArrayOut);
                byte[] data = byteArrayOut.toByteArray();
                XSSFDrawing drawingPatriarch = currentSheet.createDrawingPatriarch();

                int dx1 = 4 * Units.EMU_PER_POINT;
                int dy1 = 4 * Units.EMU_PER_POINT;
                int dx2 = -4 * Units.EMU_PER_POINT;
                int dy2 = -4 * Units.EMU_PER_POINT;
                XSSFClientAnchor anchor = new XSSFClientAnchor(dx1, dy1, dx2, dy2, cell.getColumnIndex(), currentRow.getRowNum(), cell.getColumnIndex() + 1, currentRow.getRowNum() + 1);
                anchor.setAnchorType(ClientAnchor.AnchorType.MOVE_DONT_RESIZE);
                drawingPatriarch.createPicture(anchor, workbook.addPicture(data, XSSFWorkbook.PICTURE_TYPE_JPEG));
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return cell;
    }

    public Cell writeCellImageurl(int rowSpan, int columnSpan, Consumer<Cell> cellConsumer, String imagePath) {
        Cell cell = this.writeCell(cellConsumer);
        if (columnSpan > 0) {
            this.cellIndex = this.cellIndex + columnSpan;
        }
        CellRangeAddress addresses = new CellRangeAddress(currentRow.getRowNum(),
                currentRow.getRowNum() + rowSpan, cell.getColumnIndex(), cell.getColumnIndex() + columnSpan);
        if (rowSpan > 0 || columnSpan > 0) {
            currentRow.getSheet().addMergedRegion(addresses);
            RegionUtil.setBorderBottom(cell.getCellStyle().getBorderBottom(), addresses, currentSheet);
            RegionUtil.setBorderLeft(cell.getCellStyle().getBorderLeft(), addresses, currentSheet);
            RegionUtil.setBorderRight(cell.getCellStyle().getBorderRight(), addresses, currentSheet);
            RegionUtil.setBorderTop(cell.getCellStyle().getBorderTop(), addresses, currentSheet);
        }

        String ext = FilenameUtils.getExtension(imagePath);
        try {
            //boolean urlflag=checkImgExist(imagePath);
            //if(urlflag==false){
            //    return cell;
            //}
            ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
            URL url = new URL(imagePath);
            URLConnection urlConnection =  url.openConnection();
            int status =  ((HttpURLConnection) urlConnection).getResponseCode();
            if(status!=200){
                return cell;
            }
            BufferedImage image = ImageIO.read(url);
            ImageIO.write(image, ext, byteArrayOut);
            byte[] data = byteArrayOut.toByteArray();
            XSSFDrawing drawingPatriarch = currentSheet.createDrawingPatriarch();

            int dx1 = 4 * Units.EMU_PER_POINT;
            int dy1 = 4 * Units.EMU_PER_POINT;
            int dx2 = -4 * Units.EMU_PER_POINT;
            int dy2 = -4 * Units.EMU_PER_POINT;
            XSSFClientAnchor anchor = new XSSFClientAnchor(dx1, dy1, dx2, dy2, cell.getColumnIndex(), currentRow.getRowNum(), cell.getColumnIndex() + 1, currentRow.getRowNum() + 1);
            anchor.setAnchorType(ClientAnchor.AnchorType.MOVE_DONT_RESIZE);
            drawingPatriarch.createPicture(anchor, workbook.addPicture(data, XSSFWorkbook.PICTURE_TYPE_JPEG));
        } catch (IOException e) {
            //e.printStackTrace();
        }
        finally {
            return cell;
        }
    }
    public Cell writeCellImage_row(int rowSpan, int columnSpan, Consumer<Cell> cellConsumer, String imagePath) {
        Cell cell = this.writeCell(cellConsumer);
        if (columnSpan > 0) {
            this.cellIndex = this.cellIndex + columnSpan;
        }
        CellRangeAddress addresses = new CellRangeAddress(currentRow.getRowNum(),
                currentRow.getRowNum() + rowSpan, cell.getColumnIndex(), cell.getColumnIndex() + columnSpan);
        if (rowSpan > 0 || columnSpan > 0) {
            currentRow.getSheet().addMergedRegion(addresses);
            RegionUtil.setBorderBottom(cell.getCellStyle().getBorderBottom(), addresses, currentSheet);
            RegionUtil.setBorderLeft(cell.getCellStyle().getBorderLeft(), addresses, currentSheet);
            RegionUtil.setBorderRight(cell.getCellStyle().getBorderRight(), addresses, currentSheet);
            RegionUtil.setBorderTop(cell.getCellStyle().getBorderTop(), addresses, currentSheet);
        }

        String ext = FilenameUtils.getExtension(imagePath);
        if(StringUtils.isNotEmpty(imagePath)){
            imagePath=imagePath.replaceAll("/profile","");
        }
        File photoFile = null;
        if(StringUtils.isNotEmpty(RuoYiConfig.getProfile())){
            photoFile= new File(RuoYiConfig.getProfile()+imagePath);
        }
        if(!photoFile.exists()){
            if(StringUtils.isNotEmpty(RuoYiConfig.getProfile1())){
                photoFile= new File(RuoYiConfig.getProfile1()+imagePath);
            }
        }
        if(!photoFile.exists()){
            if(StringUtils.isNotEmpty(RuoYiConfig.getProfile2())){
                photoFile= new File(RuoYiConfig.getProfile2()+imagePath);
            }
        }
        if(!photoFile.exists()){
            if(StringUtils.isNotEmpty(RuoYiConfig.getProfile3())){
                photoFile= new File(RuoYiConfig.getProfile3()+imagePath);
            }
        }
        if (photoFile.exists()) {
            BufferedImage bufferedImage = null;
            try {
                bufferedImage = ImageIO.read(photoFile);
                int widthPx = bufferedImage.getWidth();
                int heightPx = bufferedImage.getHeight();

                ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
                ImageIO.write(bufferedImage, ext, byteArrayOut);
                byte[] data = byteArrayOut.toByteArray();
                XSSFDrawing drawingPatriarch = currentSheet.createDrawingPatriarch();

                int dx1 = 4 * Units.EMU_PER_POINT;
                int dy1 = 4 * Units.EMU_PER_POINT;
                int dx2 = -4 * Units.EMU_PER_POINT;
                int dy2 = -4 * Units.EMU_PER_POINT;
                XSSFClientAnchor anchor = new XSSFClientAnchor(dx1, dy1, dx2, dy2, cell.getColumnIndex(), currentRow.getRowNum(), cell.getColumnIndex() + 1, currentRow.getRowNum() + rowSpan + 1);
                anchor.setAnchorType(ClientAnchor.AnchorType.MOVE_DONT_RESIZE);
                drawingPatriarch.createPicture(anchor, workbook.addPicture(data, XSSFWorkbook.PICTURE_TYPE_JPEG));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return cell;
    }
}
